package com.sp.scmdb.action;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.sp.scmdb.bean.TagBean;
import com.sp.scmdb.bean.UserBean;
import com.sp.scmdb.common.CommonParamter;
import com.sp.scmdb.common.action.BaseAction;
import com.sp.scmdb.entity.Tag;
import com.sp.scmdb.exception.ExcelException;
import com.sp.scmdb.service.ExportExcelService;
import com.sp.scmdb.service.TagService;

@Controller("tagsAction")
@Scope("prototype")
public class TagsAction extends BaseAction<TagBean> {

	private static final long serialVersionUID = 1L;
	private TagService tagService;
	private static Log log = LogFactory.getLog(TagsAction.class);
	private ExportExcelService exportExcelService;
	private InputStream excelStream;
	private String fileName;
	private File attachment;
	private String attachmentFileName;
	private String attachmentContentType;
	
	
	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public File getAttachment() {
		return attachment;
	}

	public InputStream getExcelStream() {
		return excelStream;
	}

	public void setExcelStream(InputStream excelStream) {
		this.excelStream = excelStream;
	}

	public void setAttachment(File attachment) {
		this.attachment = attachment;
	}

	public String getAttachmentFileName() {
		return attachmentFileName;
	}

	public void setAttachmentFileName(String attachmentFileName) {
		this.attachmentFileName = attachmentFileName;
	}

	public String getAttachmentContentType() {
		return attachmentContentType;
	}

	public void setAttachmentContentType(String attachmentContentType) {
		this.attachmentContentType = attachmentContentType;
	}

	public ExportExcelService getExportExcelService() {
		return exportExcelService;
	}

	public void setExportExcelService(ExportExcelService exportExcelService) {
		this.exportExcelService = exportExcelService;
	}

	/**
	 * @param tagService
	 *            the tagService to set
	 */
	@Autowired
	public void setTagService(TagService tagService) {
		this.tagService = tagService;
	}

	@SuppressWarnings("unchecked")
	public String findAll() {

		TagBean tagBean = null;
		if (StringUtils.isNotEmpty(pageName)) {
			tagBean = (TagBean)session.get("tagBean");
		}else{
			entity.setPageNo(1);
		}
		entity = tagService.queryTagALL(entity, tagBean);
		session.put("tagBean", entity);
		session.put("tagState", CommonParamter.TypeCommon.getTagState());
		session.put("useType", CommonParamter.TypeCommon.getUseType());
		/* 2011-05-04修改* */
		// 页面”添加“，”修改“，”删除“按钮的权限设置
		// 调用BaseAction的button(String urlAdd, String urlEdit, String urlDel)方法
		
		return SUCCESS;
	}
	public String addInitTag(){
		return "newSucc";
	}
	public String addTag() {
		try {
			Tag t = new Tag();
			t.setTagno(entity.getTagno());
			t.setUsestat("0");
			t.setPowerstat("0");
			UserBean oldUser = (UserBean)session.get("user");
			oldUser.setOldUserName(oldUser.getUserName());
			String flg = tagService.addTag(t,oldUser);
			messageSession(flg, "电子标签");
			if (log.isInfoEnabled()) {
				log.info("add suncce");
			}
		} catch (Exception e) {
			log.error("add fail,reason:" + e.getMessage());
		}
		return "commitSucc";
	}

	public String findTag() {
		try {
			String pId = request.getParameter("id");
			String Hql = "from Tag where id = " + pId;
			List<Tag> list = tagService.queryTagName(Hql);
			if (CollectionUtils.isEmpty(list)) {
				request.setAttribute("message", "电子标签号不存在！");
			} else {
				request.setAttribute("tagList", list);
			}
		} catch (Exception e) {
			log.error("add fail" + e.getMessage());
		}
		return "editSucc";
	}

	public String editTag() {
		try {
			//String Id = request.getParameter("id");
			UserBean oldUser = (UserBean)session.get("user");
			oldUser.setOldUserName(oldUser.getUserName());
			String flg = tagService.editTag(entity, oldUser);
			messageSession(flg, "电子标签");
			if (log.isInfoEnabled()) {
				log.info("edit suncce");
			}
		} catch (Exception e) {
			log.error("edit fail" + e.getMessage());
		}
		return "commitSucc";
	}

	public String delTag() {
		String flg = null;
		try {
			String pId = request.getParameter("type");
			if (StringUtils.isNotEmpty(pId)) {
				UserBean oldUser = (UserBean)session.get("user");
				oldUser.setOldUserName(oldUser.getUserName());
				String[] arr = pId.split(",");
				flg = tagService.delTag(arr,oldUser);
			}
			if ("2".equals(flg)) {
				messageSession("0", "已使用的卡号不能删除！");
			}
			if ("1".equals(flg)) {
				messageSession(flg, "RFID");
			}
			if (log.isInfoEnabled()) {
				log.info("delete suncce");
			}
		} catch (Exception e) {
			log.error("delete fail" + e.getMessage());
		}
		return "commitSucc";
	}
	public String downLoadExcel() {
		try {
			Workbook wb = new HSSFWorkbook();
			String tableName = "卡片信息模板";
			wb = exportExcelService.createTagExcel(tableName);
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			tableName = new String("卡片信息模板".getBytes(), "ISO-8859-1");
			this.fileName = tableName + ".xls";
			wb.write(out);
			excelStream = new ByteArrayInputStream(out.toByteArray());
			out.flush();
			out.close();
			return "outExcel";
		} catch (ExcelException excel) {
			log.error("create excel failed! reason:" + excel.getMessage());
			return "fail";
		} catch (Exception e) {
			log.error("excel failed! reason:" + e.getMessage());
			return "fail";
		}
	}
	public String importExcel() {
		return "importExcel";
	}
	public String commitImportExcel() {
		String result = CommonParamter.CHECK_SUCCESS;
		UserBean user = (UserBean) session.get("user");
		try {
			if (attachmentFileName.toLowerCase().endsWith("xls")) {
				String errorInfo = exportExcelService.importTagExcel(attachment, attachmentFileName, user);
				if (StringUtils.isNotEmpty(errorInfo)) {
					messageSession("0", errorInfo);
				} else {
					messageSession(result, "导入卡片信息");
				}
			} else {
				messageSession("0", "请输入后缀为xls的EXCEL文件路径！");
			}
			return "commitSucc";
		} catch (Exception e) {
			log.error("import excel failed! reason:" + e.getMessage());
			return "fail";
		}
	}

}
